package com.sdyd.antivirus.controller;

import com.alibaba.fastjson.JSONObject;
import com.sdyd.antivirus.model.GlobalVar;
import com.sdyd.antivirus.model.GroupInfo;
import com.sdyd.antivirus.service.GroupInfoService;
import com.sdyd.antivirus.service.HealthCollectionService;
import com.sdyd.antivirus.utils.DownloadFileUtil;
import com.sdyd.antivirus.utils.QRCodeUtil;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;

@Controller
public class GroupInfoController {

    Logger logger=LoggerFactory.getLogger(GroupInfoController.class);
    @Autowired
    private HealthCollectionService healthCollectionService;
    @Autowired
    private GroupInfoService groupInfoService;
    @Autowired
    private GlobalVar globalVar;


    /**
     * 首页数据获取
     *
     * @
     */
    @RequestMapping(value = "/addGroupdata")
    @ResponseBody
    public String groupData(GroupInfo record) {
        String resultData = "";
        JSONObject obj = new JSONObject();
        obj.put("success",true);
        try{

            resultData = healthCollectionService.addGroupData(record);

        }catch (Exception e){
            e.printStackTrace();
            logger.error("插入单位信息失败："+e.getMessage());
            obj.put("success",false);
            obj.put("msg","提交失败，请联系管理员，谢谢使用");
            resultData = obj.toString();
        }

        return resultData;

    }

    /**
     * 首页数据获取
     *
     * @
     */
    @RequestMapping(value = "/QRCode")
    @ResponseBody
    public Object QRCode(@RequestParam(value = "id", required = true) String id,
                         HttpServletResponse response, HttpServletRequest request) throws Exception {
        GroupInfo groupInfo = groupInfoService.get(id);
        String PERSON_HEALTH_ADDRESS_PRE = globalVar.Base_Url_Path + "/HealthReporting/user?groupId=";
        String url = PERSON_HEALTH_ADDRESS_PRE + groupInfo.getId();
        String path = globalVar.LOCAL_P_PATH + File.separator + "p-" + groupInfo.getId() + ".png";
        QRCodeUtil.encode(url, path);

        String PATH = globalVar.LOCAL_P_PATH;
        String FILENAME = "p-" + groupInfo.getId() + ".png";
        ResponseEntity<InputStreamResource> responseEntity = null;
        try {
            responseEntity = DownloadFileUtil.downloadJpg(PATH, FILENAME, FILENAME);
        } catch (Exception e) {
            logger.error("加载二维码失败");
        }
        return responseEntity;

    }

}
